<?php

require_once("GlobalSettings.php");
require_once("user/UserManager.php");
require_once("resource/FileResourceManager.php");

class UploadManager
{	 

   protected $currentUploadFile = NULL;
   protected $databaseFileInfo = NULL;
   
   public function __construct()
   {
   }
   
   public function __destruct()
   {
      if(NULL !=$this->currentUploadFile)
	  {
	     $this->abortUploadFile();
	  }
   }
  
   /*
   *return the destination file name and begin a transaction.
   *return NULL if upload is not allowed.
   */
   public function beginUploadFile($user,$sourceFileInfoArray,$uploadInfoArray)
   {
	 
	  $sourceFileName = $sourceFileInfoArray["name"];
	  $destinationFileName =  //generate unique destination file name.
	  uniqid(rand())."_".time() . "." . pathinfo($sourceFileName, PATHINFO_EXTENSION);
	  
	  $absoluteFilePath = GlobalSettings::instance()->getSetting(
		GlobalSettings::COURSEWARE_ROOT_PATH
		);
	
	  $relativeFilePath = $user->ID;
	  $absoluteFilePath .= "/" . $relativeFilePath;	  
	  
	  if(!is_dir($absoluteFilePath) && !mkdir($absoluteFilePath,0777,true))
	  {
	     throw new Exception("Failed to create dir:" . $absoluteFilePath);
	  }
	  
	  $relativeFilePath .= "/" . $destinationFileName;
	  $absoluteFilePath .= "/" . $destinationFileName; 
	  
	  $this->databaseFileInfo = 
	  FileResourceManager::instance()->createFileResource($user,$relativeFilePath,$uploadInfoArray);
	  if($this->databaseFileInfo == NULL)
	  {
	      return NULL;
	  }
	  
	  $this->currentUploadFile = $absoluteFilePath;
	  return $absoluteFilePath;
   }
   
   public function endUploadFile()
   {
      try
	  {
	     FileResourceManager::instance()->insertFileResource($this->databaseFileInfo);
         $this->databaseFileInfo = NULL;
		 $this->currentUploadFile = NULL;
	  }
	  catch(Exception $e)
	  {		 
	     $this->abortUploadFile();
		 throw $e;
	  }
   }
   
   public function abortUploadFile()
   {    
       if( 
	   $this->databaseFileInfo == NULL
	   ||
	   $this->currentUploadFile == NULL
	   )
	   {
	       throw new Exception("Invalid call UploadManager::abortUploadFile,no transaction found!");
	   }
       if(is_file($this->currentUploadFile) && !unlink($this->currentUploadFile))
	   {
	       throw new Exception("Failed to delete pending uploaded file!");
	   }	   
   }
   
}